package com.siyao.redvip.ui.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.HttpParams;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.siyao.redvip.R;
import com.siyao.redvip.RedApplication;
import com.siyao.redvip.bean.ResponseBean;
import com.siyao.redvip.bean.UserBean;
import com.siyao.redvip.components.base.BaseFragmentActivity;
import com.siyao.redvip.components.view.CircleImageView;
import com.siyao.redvip.components.view.MMAlert;
import com.siyao.redvip.image.ImageLoaderOptions;
import com.siyao.redvip.network.NetConstans;
import com.siyao.redvip.utils.AppUtils;
import com.siyao.redvip.utils.Constants;
import com.siyao.redvip.utils.PhotoUtil;
import com.siyao.redvip.utils.ToastUtils;
import com.siyao.redvip.utils.Track;
import com.siyao.redvip.volley.NetRequest;
import com.android.volley.http.RequestManager.RequestListener;
import com.android.volley.http.RequestMap;
import com.android.volley.http.RequestManager;
import com.android.volley.http.LoadControler;

/**
 * 主界面
 * 
 * @author wangxuebin
 * 
 */
public class RedvipMainActivity extends BaseFragmentActivity {

	private CircleImageView userIcon;

	private TextView userName,userNum;

	private LinearLayout btnHygl, btnHdxx, btnFriend, btnPhb, btnJkzx;
	private UserBean user;
	private String tp = "";
	
	String filePath = "";
	Bitmap newBitmap;
	boolean isFromCamera = false;// 区分拍照旋转
	String path = "";
	int degree = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleText("红色会员");
		setRightButton(R.drawable.btn_menu_selector);
	}

	@SuppressLint("InflateParams")
	@Override
	public void ininlazeLayout() {
		View appView = getLayoutInflater().inflate(
				R.layout.activity_main_fragment, null);
		appMainView.addView(appView, layoutParams);
	}

	@Override
	public void ininlazeView() {
		userIcon = (CircleImageView) findViewById(R.id.user_icon);
		userName = (TextView) findViewById(R.id.user_name);
		userNum = (TextView) findViewById(R.id.user_num);
		btnHygl = (LinearLayout) findViewById(R.id.hygl);
		btnHdxx = (LinearLayout) findViewById(R.id.hdxx);
//		btnPhoto = (Button) findViewById(R.id.btn_photo);
		btnFriend = (LinearLayout) findViewById(R.id.friend);
		btnPhb = (LinearLayout) findViewById(R.id.phb);
		btnJkzx = (LinearLayout) findViewById(R.id.jkzx);

		userIcon.setOnClickListener(this);
		btnHygl.setOnClickListener(this);
		btnHdxx.setOnClickListener(this);
//		btnPhoto.setOnClickListener(this);
		btnFriend.setOnClickListener(this);
		btnPhb.setOnClickListener(this);
		btnJkzx.setOnClickListener(this);
	}
	
	@Override
	protected void beforeInit() {
		 options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_loading).showImageForEmptyUri(R.drawable.ic_load_faild)
	                .showImageOnFail(R.drawable.ic_load_faild).cacheInMemory(true).cacheOnDisc(true).considerExifParams(true)
	                .displayer(new RoundedBitmapDisplayer(20)).build();
	}
	
	@SuppressWarnings("static-access")
	@Override
	public void ininlazeData() {
		user = redApplication.getUser();
		Track.i(user.getName());
		 String headPortrait = user.getHeadPortrait();
		 if (!TextUtils.isEmpty(headPortrait)) {
			//下载头像信息缓存到本地
			imageLoader.displayImage(headPortrait, userIcon,
						ImageLoaderOptions.getHeaderOptions());
		 }
		// 设置名字
		if (!TextUtils.isEmpty(user.getName())) {
			userName.setText(user.getName() + "");
			userNum.setText(user.getVolunteerId()+"");
		}
	}

	@Override
	public void onClick(View v) {
		int vId = v.getId();
		Intent intetn;
		switch (vId) {
		case R.id.user_icon:
			addPhoto();
			break;

		case R.id.hygl:// 会员管理
			intetn = new Intent(this, VipManageActivity.class);
			jumpActivity(intetn);
			break;
		case R.id.hdxx:// 活动信息
			intetn = new Intent(this, HdxxActivity.class);
			jumpActivity(intetn);
			break;
		case R.id.friend:// 朋友圈
			intetn = new Intent(this, FriendActivity.class);
			jumpActivity(intetn);
			break;
		case R.id.jkzx:// 健康咨询
			intetn = new Intent(this, ZxActivity.class);
			jumpActivity(intetn);
			break;
		case R.id.phb:// 排行榜
			ToastUtils.makeMesageLong(this, "该功能正在完善中，敬请期待！");
			break;
		case R.id.top_right_btn_image:
			intetn = new Intent(this, PopDialogActivity.class);
			jumpActivity(intetn);
			break;
		}
	}

	/**
	 * 退出方法
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			dialog();
			return false;
		}
		return false;
	}

	/**
	 * 弹出退出对话框
	 */
	protected void dialog() {
		AlertDialog.Builder builder = new Builder(RedvipMainActivity.this);
		builder.setMessage("确定要退出吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						RedvipMainActivity.this.finish();
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			if (requestCode == Constants.IMAGEDITAL && resultCode == RESULT_OK) {

			} else if (requestCode == Constants.REQUESTCODE_UPLOADAVATAR_CAMERA
					&& resultCode == RESULT_OK) {// 拍照修改头像
				if (!Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					ToastUtils.makeMesageShort(this, "SD卡不可以");
					return;
				}
				isFromCamera = true;
				File file = new File(filePath);
				degree = PhotoUtil.readPictureDegree(file.getAbsolutePath());
				Track.i("拍照后的角度：" + degree);
				startImageAction(Uri.fromFile(file), 200, 200,
						Constants.REQUESTCODE_UPLOADAVATAR_CROP, true);
			} else if (requestCode == Constants.REQUESTCODE_UPLOADAVATAR_CAMERA
					&& resultCode == RESULT_OK) {// 拍照修改头像
				if (!Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					ToastUtils.makeMesageShort(this, "SD卡不可以");
					return;
				}
				isFromCamera = true;
				File file = new File(filePath);
				degree = PhotoUtil.readPictureDegree(file.getAbsolutePath());
				Log.i("life", "拍照后的角度：" + degree);
				startImageAction(Uri.fromFile(file), 200, 200,
						Constants.REQUESTCODE_UPLOADAVATAR_CROP, true);
			} else if (Constants.REQUESTCODE_UPLOADAVATAR_LOCATION == requestCode) {// 本地修改头像
				Uri uri = null;
				if (data == null) {
					return;
				}
				if (resultCode == RESULT_OK) {
					if (!Environment.getExternalStorageState().equals(
							Environment.MEDIA_MOUNTED)) {
						Toast.makeText(this, "SD卡不可用", Toast.LENGTH_SHORT)
								.show();
						return;
					}
					isFromCamera = false;
					uri = data.getData();
					String imgName = "image" + System.currentTimeMillis()
							+ ".png";
					SaveImgTask saveImgTask = new SaveImgTask();
					saveImgTask.uri = uri;
					saveImgTask.imgName = imgName;
					saveImgTask.execute(100);
				} else {
					Toast.makeText(this, "照片获取失败", Toast.LENGTH_SHORT).show();
				}
			} else if (requestCode == Constants.REQUESTCODE_UPLOADAVATAR_CROP) {
				if (data == null) {
					return;
				}
				saveCropAvator(data);
				// 初始化文件路径
				filePath = "";
				// 上传头像
				uploadUserHead(path);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 图片选择handler
	 */
	Handler chooseImgHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			dismissPd();
			try {
				switch (msg.what) {
				case Constants.uploadHeadimgOK:
					String headimg = (String) msg.obj;
					RedApplication.getInstance().getUser()
							.setHeadPortrait(headimg);
					
					AppUtils.deleteAllFiles(new File(
							Constants.APP_FILE_DIR));
					imageLoader.clearDiscCache();
					imageLoader.clearMemoryCache();
					
					ImageLoader.getInstance().displayImage(
							headimg, userIcon,
							ImageLoaderOptions.getHeaderOptions());
					Intent intent = new Intent(
							Constants.PERSONAL_IMG_CHANGE_REQCODE);
					intent.putExtra("headimg", headimg);
					RedvipMainActivity.this.sendBroadcast(intent);
					break;
				case Constants.uploadHeadimgFaild:
					ToastUtils.makeMesageShort(RedvipMainActivity.this,
							"头像上传失败");
					break;
				default:
					break;
				}
			} catch (Exception e) {
			}
		}
	};

	/**
	 * 添加照片
	 */
	private void addPhoto() {
		final String[] addPhoto = { "拍照", "从手机相册选择" };
		MMAlert.showAlert(this, null, addPhoto, null,
				new MMAlert.OnAlertSelectId() {
					@Override
					public void onClick(int whichButton) {
						switch (whichButton) {
						case 0: { // 拍照
							takePic();
							break;
						}
						case 1: { // 从相册选择
							choosePic();
							break;
						}
						}
					}
				});
	}

	/**
	 * 拍照
	 */
	public void takePic() {
		File dir = new File(Constants.IMAGE_CACHE_DIR);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		// 原图
		File file = new File(dir,
				new SimpleDateFormat("yyMMddHHmmss").format(new Date()));
		filePath = file.getAbsolutePath();// 获取相片的保存路径
		Uri imageUri = Uri.fromFile(file);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(intent,
				Constants.REQUESTCODE_UPLOADAVATAR_CAMERA);
	}

	public void choosePic() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent,
				Constants.REQUESTCODE_UPLOADAVATAR_LOCATION);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	private void startImageAction(Uri uri, int outputX, int outputY,
			int requestCode, boolean isCrop) {
		Intent intent = null;
		if (isCrop) {
			intent = new Intent("com.android.camera.action.CROP");
		} else {
			intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		}
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", outputX);
		intent.putExtra("outputY", outputY);
		intent.putExtra("scale", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra("return-data", true);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, requestCode);
	}

	/**
	 * 保存裁剪的头像
	 * 
	 * @param data
	 */
	private void saveCropAvator(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap bitmap = extras.getParcelable("data");
			Log.i("life", "avatar - bitmap = " + bitmap);
			if (bitmap != null) {
				bitmap = PhotoUtil.toRoundCorner(bitmap, 10);
				if (isFromCamera && degree != 0) {
					bitmap = PhotoUtil.rotaingImageView(degree, bitmap);
				}
				// ivUserIcon.setImageBitmap(bitmap);
				// 保存图片
				String filename = new SimpleDateFormat("yyMMddHHmmss")
						.format(new Date()) + ".png";
				path = Constants.SAVE_IMAGE_PATH_IMGS + filename;
				PhotoUtil.saveBitmap(Constants.SAVE_IMAGE_PATH_IMGS, filename,
						bitmap, true);
				// 上传头像
				if (bitmap != null && bitmap.isRecycled()) {
					bitmap.recycle();
				}
			}
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param tp
	 */
	/**
	 * 修改用户头像
	 */
	public void uploadUserHead(final String loadImg) {
		if (TextUtils.isEmpty(loadImg)) {
			return;
		}
		showPd();
		new Thread(new Runnable() {
			public void run() {
				try {
					String loadImgTemp = AppUtils.removeFileHeader(loadImg);
					if (TextUtils.isEmpty(loadImgTemp)) {
						return;
					}
					File fileNew = AppUtils.copeFile(new File(loadImgTemp));
					String fileName = AppUtils.getFileName(fileNew
							.getAbsolutePath());
					File file = new File(fileNew.getAbsolutePath());
					RequestMap params = new RequestMap();
					params.put("volunteerId", RedApplication.getInstance()
							.getUser().getVolunteerId()
							+ "");
					params.put("headPortrait", file);

					RequestManager.getInstance(
							RedvipMainActivity.this).post(
							NetConstans.UPLOADHEADIMG_URL, params,
							new RequestListener() {
								@Override
								public void onSuccess(String response,
										String url, int actionId) {
									Track.i("OnSucess!\n" + response);
									ResponseBean reBean = gson.fromJson(
											response,
											new TypeToken<ResponseBean>() {
											}.getType());
									Message message = new Message();
									if (reBean.getStatus() == 1) {
										message.what = Constants.uploadHeadimgOK;
										message.obj = reBean.getData()
												.getHeadPortrait();
									} else {
										message.what = Constants.uploadHeadimgFaild;
									}
									chooseImgHandler.sendMessage(message);
								}

								@Override
								public void onError(String errorMsg,
										String url, int actionId) {
									Track.i(" onError!\n" + errorMsg);
								}

								@Override
								public void onRequest() {
									Track.i("request send...");
								}
							}, 2);
				} catch (Exception e) {
					e.printStackTrace();
					Message message = new Message();
					message.what = Constants.uploadHeadimgFaild;
					chooseImgHandler.sendMessage(message);
				}
			}
		}).start();
	}

	class SaveImgTask extends AsyncTask<Integer, Integer, Boolean> {

		private String imgName;
		private Uri uri;

		@Override
		protected void onPreExecute() {
			showPd();
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			// 这个方法是根据Uri获取Bitmap图片的静态方法
			Bitmap bitmap = null;
			try {
				bitmap = MediaStore.Images.Media.getBitmap(
						RedvipMainActivity.this.getContentResolver(), uri);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			if (bitmap != null) {
				File tempFile = new File(Constants.SAVE_IMAGE_PATH_IMGS);
				if (!tempFile.exists()) {
					tempFile.mkdirs();
				}
				AppUtils.saveBitmap(Constants.SAVE_IMAGE_PATH_IMGS, imgName,
						bitmap);
				try {
					if (!bitmap.isRecycled()) {
						bitmap.recycle();
						bitmap = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			dismissPd();
			if (result) {
				try {
					File imageFile = new File(Constants.SAVE_IMAGE_PATH_IMGS
							+ imgName);
					if (!imageFile.exists()) {
						return;
					}
					startImageAction(Uri.fromFile(imageFile), 200, 200,
							Constants.REQUESTCODE_UPLOADAVATAR_CROP, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			super.onPostExecute(result);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
